﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAO;
using DTO;

namespace BUS
{
    public class InvoiceBUS
    {
        InvoiceDAO invoiceDAO = new InvoiceDAO();

        public bool CheckQuantityStockAfterSell(int quantity)
        {
            try
            {
                ParameterDAO paraDAO = new ParameterDAO();
                int stockquantity = paraDAO.GetParameterValueByCode(ParameterCode.MinAfterSell.ToString());
                if (quantity < stockquantity)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }

        public bool InsertInvoiceList(InvoiceDTO invoice)
        {
            try
            {
                invoice.InvoiceID = invoiceDAO.InsertInvoice(invoice);
                if (invoice.InvoiceID > 0)
                {
                    foreach (InvoiceDetailDTO invoiceDetail in invoice.ListInvoiceDetail)
                    {
                        invoiceDetail.InvoiceID = invoice.InvoiceID;
                        invoiceDetail.InvoiceDetailID = invoiceDAO.InsertInvoiceDetail(invoiceDetail);

                        BookDAO bookDAO = new BookDAO();
                        bookDAO.UpdateQuantityFromReceiving(invoiceDetail.BookID, -invoiceDetail.Quantity);
                    }

                    CustomerBUS customerBUS = new CustomerBUS();
                    customerBUS.UpdateCustomerDebtFromInvoice(invoice.CustomerID, invoice.GrandTotal);

                    return true;
                }
                else
                {
                    return false;
                }     
            }
            catch
            {
                return false;
            }
        }
        
    }
}
